<script lang="ts" setup>
import { computed, h, onMounted, ref } from 'vue';
import { NButton, useMessage } from 'naive-ui';
import type { TableColumn } from 'naive-ui/es/data-table/src/interface';
import { useLoading } from '~/packages/hooks';
import { $t } from '@/locales';

import { addAiConfig, deleteAiConfig, getAiConfigList, updateAiConfig } from '@/service/api';
import { toFullModel } from '@/utils/common';

const message = useMessage();
const { loading, startLoading, endLoading } = useLoading();

const configList = ref<Api.AiConfig.Info[]>([]);
const showModal = ref(false);
const modalType = ref<'add' | 'edit'>('add');
const currentItem = ref<Api.Configure.Info | null>(null);


const formRef = ref();
const formModel = ref<Partial<Api.AiConfig.AddOrEdit>>({
  type: 0
});
const formRules = {
  name: { required: true, message: $t('page.aiConfig.nameRequired'), trigger: 'blur' },
  token: { required: true, message: $t('page.aiConfig.tokenRequired'), trigger: 'blur' },
  url: { required: true, message: $t('page.aiConfig.urlRequired'), trigger: 'blur' },
  type: { required: true, message: $t('page.aiConfig.typeRequired'), trigger: 'blur' }
};

const handleEdit = (item: Api.Configure.Info) => {
  modalType.value = 'edit';
  currentItem.value = { ...item };
  formModel.value = { ...item };
  showModal.value = true;
};

const fetchConfigList = async () => {
  try {
    // 这里应该调用获取配置列表的API
    const { error, data } = await getAiConfigList();
    if (!error) configList.value = data;
  } catch {
    message.error($t('request.AcquisitionFailed'));
  }
};

const handleDelete = async (id: string | undefined) => {
  if (!id) {
    message.error($t('common.selectDataMsg'));
    return;
  }
  try {
    // 这里应该调用删除API
    await deleteAiConfig(id);
    fetchConfigList();
  } catch {
    message.error($t('common.deleteFailed'));
  }
};

const columns = computed<TableColumn<any>[]>(() => [
  { title: $t('page.aiConfig.nameRequired'), key: 'name' },
  { title: $t('page.aiConfig.tokenRequired'), key: 'token' },
  { title: $t('page.aiConfig.urlRequired'), key: 'url' },
  { title: $t('page.aiConfig.typeRequired'), key: 'type' },
  { title: $t('page.aiConfig.balanceRequired'), key: 'balance' },
  { title: $t('page.aiConfig.maxLengthRequired'), key: 'maxLength' },
  {
    title: $t('common.action'),
    key: 'actions',
    align: 'center',
    render(row: Api.Configure.Info) {
      return h('NSpace', {}, [
        h(NButton, { type: 'primary', size: 'small', onClick: () => handleEdit(row) }, $t('common.edit')),
        h(NButton, { type: 'error', class: 'ml-5px', size: 'small', onClick: () => handleDelete(row.id) }, $t('common.delete'))
      ]);
    }
  }
]);

const handleAdd = () => {
  modalType.value = 'add';
  formModel.value = {
    type: 0
  };
  showModal.value = true;
};

/** 批量删除 */
const handleBateDelete = () => {
  // 触发批量删除
};

const handleSubmit = () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      try {
        startLoading();
        const datas = toFullModel(formModel.value);
        if (modalType.value === 'add') {
          // 这里应该调用添加API
          await addAiConfig(datas);
        } else {
          // 这里应该调用更新API
          if (!currentItem.value!.id) {
            message.error($t('common.selectDataMsg'));
            return;
          }
          await updateAiConfig({ ...datas, id: currentItem.value!.id } as Api.AiConfig.AddOrEdit);
        }
        showModal.value = false;
        fetchConfigList();
      } catch {
        message.error(modalType.value === 'add' ? $t('common.addFailed') : $t('common.updateFailed'));
      } finally {
        endLoading();
      }
    }
  });
};

onMounted(() => {
  fetchConfigList();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :bordered="false">
      <TableHeaderOperation
        v-model:columns="columns as NaiveUI.TableColumnCheck[]"
        :loading="loading"
        @add="handleAdd"
        @delete="handleBateDelete"
        @refresh="fetchConfigList"
      />
      <!--          @delete="handleDelete"-->
      <NDataTable
        :columns="columns"
        :data="configList"
        :pagination="{
          pageSize: 10,
          showSizePicker: true,
          pageSizes: [10, 20, 30, 40],
          showQuickJumper: true
        }"
        :scroll-x="1000"
      />
    </NCard>

    <NModal v-model:show="showModal" :mask-closable="true">
      <NCard
        :bordered="false"
        :title="modalType === 'add' ? $t('common.add') : $t('common.edit')"
        aria-modal="true"
        class="w-600px "
        role="dialog"
        size="huge"
      >
        <NForm
          ref="formRef"
          :model="formModel"
          :rules="formRules"
          :style="{ maxWidth: '640px' }"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
        >
          <NFormItem v-show="false" path="id">
            <NInput v-model:value="formModel.id" />
          </NFormItem>
          <NFormItem :label="$t('page.aiConfig.nameRequired')" path="name">
            <NInput v-model:value="formModel.name" />
          </NFormItem>
          <NFormItem :label="$t('page.aiConfig.tokenRequired')" path="token">
            <NInput v-model:value="formModel.token" />
          </NFormItem>
          <!--          <NFormItem :label="$t('page.aiConfig.typeRequired')" path="tyoe">-->
          <!--            <NSelect-->
          <!--              v-model:value="formModel.type"-->
          <!--              :options="toModel(configType)"-->
          <!--              size="small"-->
          <!--            />-->
          <!--          </NFormItem>-->
          <NFormItem :label="$t('page.aiConfig.urlRequired')" path="url">
            <NInput v-model:value="formModel.url" />
          </NFormItem>
        </NForm>

        <template #footer>
          <NSpace justify="end">
            <NButton @click="showModal = false">{{ $t('common.cancel') }}</NButton>
            <NButton :loading="loading" type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
          </NSpace>
        </template>
      </NCard>
    </NModal>
  </div>
</template>

<style scoped>

</style>
